package com.fox.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fox.config.constant.SystemConstants;
import com.fox.domain.entity.Article;
import com.fox.service.ArticleService;
import com.fox.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0/5 * * * * ?")
    public void updateViewCount(){
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.ARTICLE_VIEW_COUNT_KEY);
        List<Article> articles = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : viewCountMap.entrySet()) {
            Long articleId = Long.valueOf(entry.getKey());
            Long viewCount = Long.valueOf(entry.getValue());
            Article article = new Article(articleId,viewCount);
            articles.add(article);
        }
        //批量更新到数据库中
        articleService.updateBatchById(articles);
    }

//    @Scheduled(cron = "0/5 * * * * ?")
//    public void updateViewCount() {
//        //获取redis中浏览量数据
//        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.ARTICLE_VIEW_COUNT_KEY);
//
//        List<Article> articles = viewCountMap.entrySet()
//                .stream()
//                .map(entry ->
//                        new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
//                .collect(Collectors.toList());
//
//        for (Article article : articles) {
//            LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.eq(Article::getId, article.getId());
//            updateWrapper.set(Article::getViewCount, article.getViewCount());
//            articleService.update(updateWrapper);
//        }
//    }


}

